﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class TechniqueForm : Form
    {
        tb_technique technique;
        string action = string.Empty;
        bool updaterec = true;
        int techid, avpID, regID;

        const string catTechState = "TechState", catTechKind = "TechKind";

        public TechniqueForm()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void TechniqueForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }
            groupBox1.Enabled = false;
            nudReleaseYear.Maximum = nudReleaseYear.Value = DateTime.Now.Year;

            cbCondition.DataSource = UtilClass.FillCBCategory(catTechState);
            cbCondition.DisplayMember = "Name";
            cbCondition.ValueMember = "ID";
            cbCondition.SelectedIndex = -1;
            cbCondition.Text = string.Empty;

            cbTechKind.DataSource = UtilClass.FillCBCategory(catTechKind);
            cbTechKind.DisplayMember = "Name";
            cbTechKind.ValueMember = "ID";
            cbTechKind.SelectedIndex = -1;
            cbTechKind.Text = string.Empty;
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex == -1)
                return;

            cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
            cbAVP.DataSource = UtilClass.FillAVP(Convert.ToInt32(cbRegion.SelectedValue));
            cbAVP.ValueMember = "ID";
            cbAVP.DisplayMember = "Name";
            cbAVP.SelectedIndex = -1;
            cbAVP.Text = string.Empty;
            cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            cbAVP.Enabled = true;
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            dgvTech.SelectionChanged -= dgvTech_SelectionChanged;
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                FillTable();
                ClearForm(false);
            }
            else
                avpID = 0;
            dgvTech.SelectionChanged += new EventHandler(dgvTech_SelectionChanged);
        }

        private void FillTable()
        {
            dgvTech.DataSource = DBClass.Tehniques.Where(wh => wh.AVPID == Convert.ToInt32(cbAVP.SelectedValue))
                                               .Select(se => new
                                               {
                                                   ID = se.ID,
                                                   TechKind = UtilClass.GetCategoryDisplayName((int)se.TechKind, "TechKind"),
                                                   Name = se.Name,
                                                   ReleaseYear = se.ReleaseYear,
                                                   Cost = se.Cost,
                                                   Condition = UtilClass.GetCategoryDisplayName((int)se.Condition, "TechState")
                                               }
                                               ).ToList();
            dgvTech.Columns[0].Visible = false;
            dgvTech.Columns[1].HeaderText = "Вид техники";
            dgvTech.Columns[2].HeaderText = "Название";
            dgvTech.Columns[3].HeaderText = "Год выпуска";
            dgvTech.Columns[4].HeaderText = "Стоимость";
            dgvTech.Columns[5].HeaderText = "Состояние";
        }

        private void dgvTech_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvTech.RowCount <= 0)
                return;

            this.groupBox1.Enabled = false;
            Int32.TryParse(dgvTech["ID", dgvTech.CurrentRow.Index].Value.ToString(), out techid);
            if (techid == 0)
                return;

            technique = DBClass.Tehniques.Where(wh => wh.ID == techid)
                                        .Select(se => se).FirstOrDefault();

            if (technique != null)
            {
                this.tbName.Text = technique.Name;
                this.tbCost.Text = technique.Cost.ToString();
                this.nudReleaseYear.Value = technique.ReleaseYear.Value;

                cbCondition.SelectedIndex = cbCondition.FindStringExact(UtilClass.GetCategoryDisplayName((int)technique.Condition, catTechState));
                cbTechKind.SelectedIndex = cbTechKind.FindStringExact(UtilClass.GetCategoryDisplayName(technique.TechKind, catTechKind));
            }
        }

        private void ClearForm(bool state)
        {
            groupBox1.Enabled = state;
            tbName.Text = tbCost.Text = string.Empty;
            nudReleaseYear.Value = DateTime.Now.Year;
            cbCondition.SelectedIndex = cbTechKind.SelectedIndex = -1;
            cbTechKind.Text = cbCondition.Text = string.Empty;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            action = "add";
            updaterec = false;
            ClearForm(true);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            action = "delete";
            if (technique != null)
            {
                DBClass.RESPContext.tb_techniques.DeleteOnSubmit(technique);
                DBClass.RESPContext.SubmitChanges();
                this.Refresh();
                ClearForm(false);
            }
        }

        private void ShowTech(bool state)
        {
            groupBox1.Enabled = state;
            tbName.Text = tbCost.Text = string.Empty;
            nudReleaseYear.Value = DateTime.Now.Year;
            cbTechKind.SelectedIndex = cbCondition.SelectedIndex = -1;
        }


        private void btnEdit_Click(object sender, EventArgs e)
        {
            action = "edit";
            updaterec = true;
            groupBox1.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbName.Text) || avpID <= 0)
            {
                MessageBox.Show("Не введено имя техники или не выбрано АВП", msgClass.msgAchtung);
                return;
            }

            decimal cost;

            if (!tbCost.Text.GetDecimalOrDefault(out cost))
            {
                if (MessageBox.Show(msgClass.msgUncorrectData_Continue, msgClass.msgAchtung, MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
            }

            if (updaterec && technique != null)
            {
                technique.Condition = Convert.ToInt32(cbCondition.SelectedValue);
                technique.Cost = cost;
                technique.Name = tbName.Text;
                technique.ReleaseYear = Convert.ToInt32(nudReleaseYear.Value);
                technique.TechKind = Convert.ToInt32(cbTechKind.SelectedValue);
            }
            else
            {
                technique = new tb_technique
                {
                    AVPID = avpID,
                    Condition = Convert.ToInt32(cbCondition.SelectedValue),
                    Cost = cost,
                    Name = tbName.Text,
                    ReleaseYear = Convert.ToInt32(nudReleaseYear.Value),
                    TechKind = Convert.ToInt32(cbTechKind.SelectedValue)
                };
                DBClass.Tehniques.InsertOnSubmit(technique);
            }
            try
            {
                DBClass.RESPContext.SubmitChanges();
                MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                FillTable();
                ClearForm(false);
            }
            catch
            {
                MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
            }
        }
    }
}
